<?php

/*

Desktopd Colors
Copyright (C) 2015  Desktopd Developer(s)

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.

https://www.gnu.org/licenses/agpl.html

*/


namespace Desktopd\Colors;

use Desktopd\Colors\PNG8PixelRGB;
use Desktopd\Colors\PNG16PixelRGB;


class PixelWalk {
    protected $walk;
    
    public function __construct ($step = 16) {
        $this->walk = new RandomWalk($step);
    }
    
    public function generate ($path) {
        if (file_exists($path)) {
            if (!is_writable($path)) {
                return false;
            }
        } else {
            if (!is_writable(dirname($path))) {
                return false;
            }
        }
        
        $this->walk->move();
        
        $sRGB = $this->walk->sRGB();
        list($R, $G, $B) = array_map(function ($c) {
            return min(65535, floor($c * 65536));
        }, array(
            $sRGB->getR(),
            $sRGB->getG(),
            $sRGB->getB()
        ));
        
        if (!function_exists('imagecreatetruecolor')) {
            return false;
        }
        
        /*
            TODO: Since 1x1 PNG images are easy, this should be a native PHP
            implementation. (using no compression if DEFLATE is not available??)
            -> Implemented
        */
        
        $result = false !== file_put_contents($path, new PNG16PixelRGB($R, $G, $B));
        /*
        $image = imagecreatetruecolor(1, 1);
        $color = imagecolorallocate($image, $R, $G, $B);
        imagefilledrectangle($image, 0, 0, 1, 1, $color);
        $result = imagepng($image, $path, 9);
        imagedestroy($image);
        */
        return $result ? "rgb($R, $G, $B)" : false;
    }
    
    public function __invoke ($path) {
        return $this->generate($path);
    }
    
    public function __toString () {
        return "{$this->walk}";
    }
    
    public function sRGB () {
        return $this->sRGB;
    }
    
    public function CIELUV () {
        return $this->walk->getCIELUV();
    }
}


// vim: ts=4 et ai

